import argparse,pathlib,re,stat,math,pwd,grp
from pathlib import Path
from datetime import datetime

def GetUsernmByUid(uid:int):
    try:
        return pwd.getpwuid(uid).pw_name
    except KeyError:
        return uid

def GetGroupnmByGid(gid:int):
    try:
        return grp.getgrgid(gid).gr_name
    except KeyError:
        return gid
def JudgeDotFile(fn:pathlib.Path) -> bool:
    regex = re.compile('\.')
    result = regex.match(fn.name)
    if result == None:
        return True
    return False
def ConverstBytes(size:int) -> str:
    if 1024000 > size >= 1024:
        return str(math.ceil(size/1024)) + 'K'
    elif 1024000000 > size >= 1024000:
        return str(math.ceil(size/1024/1024)) + 'M'
    elif 1024000000000 > size >= 1024000000:
        return str(math.ceil(size / 1024/1024/1024)) + 'G'
    elif size >= 1024000000000:
        return str(math.ceil(size / 1024/1024/1024/1024)) + 'T'
    else:
        return str(size)

parser = argparse.ArgumentParser(prog='ls',add_help=False,description='list directory contents')
parser.add_argument('path',nargs='?',default='.',help='directory')
parser.add_argument('-a','--all',action='store_true',\
                    help='show all files,do not ignore entries staring with .')
parser.add_argument('-l',action='store_true',help='display file verbose in directory')
parser.add_argument('-h',action='store_true',help='display file size by humanview')
args = parser.parse_args(['-alh','e://devops'])

p = Path(args.path)
DestDirMember=p.iterdir()
MemberList = sorted([mb for mb in DestDirMember],key=lambda x:x.name)
DstList = sorted([*filter(JudgeDotFile,MemberList)],key=lambda x:x.name)


if args.all:
    if args.l:
        if args.h:
            for x in DstList:
                print(stat.filemode(x.stat().st_mode),\
                      x.stat().st_nlink,\
                      GetUsernmByUid(x.stat().st_uid),\
                      GetGroupnmByGid(x.stat().st_gid),\
                      ConverstBytes(x.stat().st_size),\
                      datetime.fromtimestamp(int(x.stat().st_mtime)),\
                      x.name)

        else:
            for x in DstList:
                print(stat.filemode(x.stat().st_mode), \
                      x.stat().st_nlink,\
                      GetUsernmByUid(x.stat().st_uid), \
                      GetGroupnmByGid(x.stat().st_gid),\
                      x.stat().st_size,\
                      datetime.fromtimestamp(int(x.stat().st_mtime)),\
                      x.name)
    else:
        DstList = MemberList
        for x in DstList:
            print(x.name)




